package org.smherwig.wlanscanner;

import java.util.Collections;
import java.util.List;
import java.util.Timer;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TableLayout;

public class MainActivity extends Activity {
	private static final String TAG = "WiFiScanner";
	private static final int scanInterval = 10;
	private Timer timer;
	private WifiManager wifiManager;
	private WifiScanReceiver wifiReceiver;
	private ScanTableBuilder scanTableBuilder;

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WifiScanReceiver();
        scanTableBuilder = new ScanTableBuilder(this, 
        		(TableLayout) findViewById(R.id.scanResultsTable));
        timer = new Timer(TAG);
        
    }

    
    @Override
    protected void onResume() {
    	super.onResume();
    	registerReceiver(
    			wifiReceiver, 
    			new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    	timer.schedule(new ScanTask(wifiManager), 0, scanInterval * 1000);
    	
    }
    
    @Override
    protected void onPause() {
    	super.onResume();
    	timer.cancel();
    	unregisterReceiver(wifiReceiver);
    }

    class WifiScanReceiver extends BroadcastReceiver {    		
    	@Override
    	public void onReceive(Context c, Intent intent) {
    		scanTableBuilder.clearTable();
    		scanTableBuilder.createHeader();
    		List<ScanResult> scanResults = wifiManager.getScanResults();
    		Collections.sort(scanResults, new ScanResultComparator());
    		for (ScanResult result : scanResults) {
    			scanTableBuilder.createScanRow(result);
    		}
    	}
    }
    

}
